package router

import (
	"fmt"
	"service/components"
	"service/modules"
	"service/utils"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func MenuRouter(group *gin.RouterGroup) {
	group.POST("", func(context *gin.Context) {
		m := modules.Menu{}
		err := context.ShouldBind(&m)
		if err != nil {
			utils.HandleFailResponse(context, "数据错误", err.Error())
			return
		}
		err = modules.PostMenuService(&m)
		if err != nil {
			utils.HandleFailResponse(context, "创建菜单失败!", err.Error())
			return
		}
		utils.HandleSuccessResponse(context, "创建菜单成功!", m)
	})

	group.GET("", func(context *gin.Context) {
		ids := context.Query("ids")
		m, err := modules.FetchMenuService(ids)
		var rm []*modules.Menu
		if err != nil {
			utils.HandleFailResponse(context, "获取菜单失败", err.Error())
			return
		}
		i := 0
		for _, menu := range m {
			if menu.IsParent == 0 {
				rm = append(rm, menu)
				i += 1
			}
		}
		for _, Menu := range rm {
			for _, menu := range m {
				if Menu.ID == menu.IsParent {
					Menu.Children = append(Menu.Children, *menu)
				}
			}
		}
		utils.HandleSuccessResponse(context, "获取菜单成功!", gin.H{
			"list":  rm,
			"total": i,
		})
	})

	group.PATCH("", func(context *gin.Context) {
		m := &modules.Menu{}
		err := context.ShouldBind(&m)
		if err != nil {
			utils.HandleFailResponse(context, "查找失败!", err.Error())
			return
		}
		err = modules.PatchMenuService(m)
		fmt.Println(err)
		if err != nil {
			utils.HandleFailResponse(context, "更新失败", err.Error())
			return
		}
		utils.HandleSuccessResponse(context, "更新成功!", m)
	})

	group.DELETE("", func(context *gin.Context) {
		m := &modules.Menu{}
		err := context.ShouldBind(&m)
		if err != nil {
			utils.HandleFailResponse(context, "数据绑定失败!", err.Error())
			return
		}
		depart, _ := modules.FetchDepartmentService()
		for _, department := range depart {
			// 1. 删除部门的ID
			PerArray := strings.Split(department.Permissions, ",")
			for _, perStr := range PerArray {
				if perStr == fmt.Sprintf("%d", m.ID) {
					newPer := utils.ArrarFilterString(PerArray, fmt.Sprintf("%d", m.ID))
					modules.PatchDepartmentService(&modules.Department{
						Model:       gorm.Model{ID: department.ID},
						Permissions: strings.Join(newPer, ","),
						Name:        department.Name,
						MustSign:    department.MustSign,
						OrSign:      department.OrSign,
						Notify:      department.Notify,
					})
				}
			}
		}
		users, _ := modules.FindAllUserService()
		for _, user := range users {
			PerArray := strings.Split(user.Permissions, ",")
			for _, perStr := range PerArray {
				if perStr == fmt.Sprintf("%d", m.ID) {
					newPer := utils.ArrarFilterString(PerArray, fmt.Sprintf("%d", m.ID))
					components.DB.Model(&modules.Users{}).
						Where("id = ?", user.Id).
						Update("permissions", strings.Join(newPer, ","))
				}
			}
		}
		components.DB.Model(&modules.Menu{}).Where("id = ?", m.ID).Delete(&modules.Menu{})
		utils.HandleSuccessResponse(context, "删除成功!", m)
	})
}
